package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketComment;
import com.cskaoyan.market.service.AdminCommentService;
import com.cskaoyan.market.service.impl.AdminCommentServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/comment/*")
public class AdminCommentController extends HttpServlet {
    AdminCommentService adminCommentService = new AdminCommentServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/comment/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    //http://101.43.69.31:8083/admin/comment/list?page=1&limit=20
    // &userId=1&valueId=23&sort=add_time&order=desc
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String userId = req.getParameter("userId");
        String valueId = req.getParameter("valueId");
        List<MarketComment> marketGoodsList = adminCommentService.list(page, limit, sort, order, userId, valueId);
        Object o = ResponseUtil.okList(marketGoodsList);
        String s = JacksonUtil.writeValueAsString(o);
        resp.getWriter().println(s);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/comment/", "");
        if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        String id = JacksonUtil.parseString(requestBody, "id");
        Integer integer = adminCommentService.delete(id);
        Object ok = ResponseUtil.ok();
        String s = JacksonUtil.writeValueAsString(ok);
        resp.getWriter().println(s);
    }
}
